﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ActivitiesControl.Domain.DAL;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Security.Cryptography;
using ActivitiesControl.Domain.Model.Entities;

namespace ActivitiesControl.Domain.Model
{
	internal class UserHandler
	{
		private IUserRepository repository;

		internal UserHandler(IUserRepository repository)
		{
			this.repository = repository;
		}

		internal void ChangePassword(
			string login, 
			string currentPassword, 
			string newPassword, 
			string newPasswordConfirmation)
		{
			User user = repository.GetUserByLogin(login);

			if (user == null)
				throw new DomainException(string.Format("Não foi possível encontrar o usuário com o login '{0}'", login));

			user = repository.GetUserByLoginPassword(login, MD5SumTool.StringToMD5Sum(currentPassword));

			if (user == null)
				throw new DomainException("Senha atual inválida.");

			if (!newPassword.Equals(newPasswordConfirmation))
				throw new DomainException("A confirmação da nova senha não está correta.");

			user.Password = MD5SumTool.StringToMD5Sum(newPassword);

			repository.Update(user);
		}

		internal bool Validate(
			string login, 
			string password, 
			out User validatedUser)
		{
			validatedUser = repository.GetUserByLoginPassword(login, MD5SumTool.StringToMD5Sum(password));

			bool validated = false;

			if (validatedUser == null)
				throw new DomainException("Combinação usuário/senha inválida.");
			else
				validated = true;

			return validated;
		}

		private class MD5SumTool
		{
			internal static string StringToMD5Sum(string text)
			{
				BinaryFormatter bf = new BinaryFormatter();
				MemoryStream ms = new MemoryStream();

				bf.Serialize(ms, text);
				ms.Seek(0, 0);

				return BitConverter.ToString(
					new MD5CryptoServiceProvider()
						.ComputeHash(ms.ToArray())
						).Replace("-", "").ToLower();
			}
		}
	}
}